// 管理员相关功能

// 检查管理员是否已登录
function checkAdminLogin() {
    const isAdmin = localStorage.getItem('isAdmin');
    const adminUsername = localStorage.getItem('adminUsername');
    
    if (!isAdmin && window.location.pathname !== '/knowledge-qa/static/pages/admin_login.html') {
        // 如果不是管理员且不在登录页面，重定向到登录页面
        window.location.href = '/knowledge-qa/static/pages/admin_login.html';
        return false;
    }
    
    // 如果是管理员，更新欢迎信息
    if (isAdmin && adminUsername && document.getElementById('welcomeText')) {
        document.getElementById('welcomeText').textContent = `欢迎，${adminUsername}`;
    }
    
    return true;
}

// 管理员登录
function adminLogin() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    if (!username || !password) {
        showMessage('请输入用户名和密码', false);
        return;
    }
    
    // 发送登录请求
    fetch('/knowledge-qa/api/admin/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({username, password})
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 保存管理员信息到localStorage
            localStorage.setItem('adminId', data.data.adminId);
            localStorage.setItem('adminUsername', data.data.adminUsername);
            localStorage.setItem('isAdmin', true);
            
            // 跳转到管理员后台首页
            window.location.href = '/knowledge-qa/static/pages/admin_dashboard.html';
        } else {
            showMessage(data.message || '登录失败', false);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        showMessage('登录失败，请稍后重试', false);
    });
}

// 页面加载完成后检查登录状态
window.addEventListener('DOMContentLoaded', function() {
    checkAdminLogin();
    
    // 如果是在管理后台首页，加载统计数据
    if (window.location.pathname === '/knowledge-qa/static/pages/admin_dashboard.html') {
        loadDashboardStats();
        loadRecentActivities();
    }
});

// 管理员退出登录
function adminLogout() {
    if (confirm('确定要退出登录吗？')) {
        // 清除localStorage中的管理员信息
        localStorage.removeItem('adminId');
        localStorage.removeItem('adminUsername');
        localStorage.removeItem('isAdmin');
        
        // 跳转到管理员登录页面
        window.location.href = '/knowledge-qa/static/pages/admin_login.html';
    }
}

// 加载管理后台内容
function loadAdminContent(contentType) {
    const contentDiv = document.getElementById('adminContent');
    const menuItems = document.querySelectorAll('.menu-item');
    
    // 更新菜单项激活状态
    menuItems.forEach(item => {
        item.classList.remove('active');
        if (item.textContent.trim() === {
            'dashboard': '首页概览',
            'users': '用户管理',
            'questions': '问题管理',
            'answers': '回答管理',
            'transactions': '金币交易'
        }[contentType]) {
            item.classList.add('active');
        }
    });
    
    // 显示加载中状态
    contentDiv.innerHTML = '<div style="text-align: center; padding: 40px;"><p>加载中...</p></div>';
    
    // 根据内容类型加载对应HTML片段
    let htmlFile = '';
    switch(contentType) {
        case 'dashboard':
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/dashboard.html';
            break;
        case 'users':
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/users.html';
            break;
        case 'questions':
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/questions.html';
            break;
        case 'answers':
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/answers.html';
            break;
        case 'transactions':
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/transactions.html';
            break;
        default:
            htmlFile = '/knowledge-qa/static/pages/admin_fragments/dashboard.html';
    }
    
    // 发送请求加载HTML内容
    fetch(htmlFile)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载页面失败');
            }
            return response.text();
        })
        .then(html => {
            // 将加载的HTML内容设置到contentDiv中
            contentDiv.innerHTML = html;
            
            // 根据内容类型执行相应的初始化操作
            switch(contentType) {
                case 'dashboard':
                    loadDashboardStats();
                    loadRecentActivities();
                    break;
                case 'users':
                    loadUserList();
                    break;
                case 'questions':
                    loadQuestionList();
                    break;
                case 'answers':
                    loadAnswerList();
                    break;
                case 'transactions':
                    loadTransactionList();
                    break;
            }
        })
        .catch(error => {
            console.error('加载页面失败:', error);
            contentDiv.innerHTML = '<div style="text-align: center; padding: 40px; color: #ff4d4f;"><p>加载失败，请稍后重试</p></div>';
        });
}

// 加载首页统计数据
function loadDashboardStats() {
    // 加载用户总数
    fetch('/knowledge-qa/api/admin/stats/users')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && document.getElementById('totalUsers')) {
                document.getElementById('totalUsers').textContent = data.data && data.data.count ? data.data.count : 0;
            }
        })
        .catch(error => console.error('加载用户总数失败:', error));
    
    // 加载问题总数
    fetch('/knowledge-qa/api/admin/stats/questions')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && document.getElementById('totalQuestions')) {
                document.getElementById('totalQuestions').textContent = data.data && data.data.count ? data.data.count : 0;
            }
        })
        .catch(error => console.error('加载问题总数失败:', error));
    
    // 加载回答总数
    fetch('/knowledge-qa/api/admin/stats/answers')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && document.getElementById('totalAnswers')) {
                document.getElementById('totalAnswers').textContent = data.data && data.data.count ? data.data.count : 0;
            }
        })
        .catch(error => console.error('加载回答总数失败:', error));
    

}

// 加载悬赏排行前三的问题
function loadRecentActivities() {
    // 修改标题为悬赏排行
    const sectionTitle = document.querySelector('.section-title');
    if (sectionTitle && sectionTitle.textContent.includes('最近活动')) {
        sectionTitle.textContent = '悬赏排行';
    }
    
    // 获取悬赏排行前三的问题
    fetch('/knowledge-qa/api/admin/questions/rewarded-top3')
        .then(response => response.json())
        .then(data => {
            const tableBody = document.getElementById('recentActivitiesTable');
            if (data.code === 200 && tableBody) {
                const questions = data.data || [];
                
                // 如果没有数据，显示提示
                if (questions.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #999;">暂无悬赏问题</td></tr>';
                    return;
                }
                
                let html = '';
                questions.forEach((question, index) => {
                    // 添加排名样式
                    let rankStyle = '';
                    if (index === 0) rankStyle = 'background-color: #fff7e6;';
                    if (index === 1) rankStyle = 'background-color: #f0f0f0;';
                    if (index === 2) rankStyle = 'background-color: #fff0e6;';
                    
                    html += `
                        <tr style="${rankStyle}">
                            <td>${index + 1}</td>
                            <td>${question.title || '-'}</td>
                            <td>${question.coinReward || 0}</td>
                            <td>${question.username || '未知用户'}</td>
                            <td>${formatDate(question.createTime)}</td>
                        </tr>
                    `;
                });
                
                tableBody.innerHTML = html;
                
                // 修改表头
                const tableHeader = tableBody.parentElement.querySelector('thead tr');
                if (tableHeader) {
                    tableHeader.innerHTML = `
                        <th>排名</th>
                        <th>问题标题</th>
                        <th>悬赏金币</th>
                        <th>提问用户</th>
                        <th>发布时间</th>
                    `;
                }
            }
        })
        .catch(error => {
            console.error('加载悬赏排行失败:', error);
            const tableBody = document.getElementById('recentActivitiesTable');
            if (tableBody) {
                tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #ff4d4f;">加载失败，请稍后重试</td></tr>';
            }
        });
}

// 加载用户列表
function loadUserList(page = 1) {
    const userTableBody = document.getElementById('userTableBody');
    const pagination = document.getElementById('userPagination');
    const loadingIndicator = document.getElementById('loadingIndicator');
    
    // 获取搜索关键词
    let keyword = '';
    if (document.getElementById('userSearchInput')) {
        keyword = document.getElementById('userSearchInput').value;
    }
    
    if (loadingIndicator) {
        loadingIndicator.style.display = 'block';
    }
    
    fetch(`/knowledge-qa/api/admin/users?page=${page}&pageSize=10&keyword=${encodeURIComponent(keyword)}`)
        .then(response => response.json())
        .then(data => {
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            
            if (data.code === 200 && userTableBody) {
                const users = data.data.users || [];
                const total = data.data.total || 0;
                const pageSize = data.data.pageSize || 10;
                const totalPages = Math.ceil(total / pageSize);
                
                if (users.length === 0) {
                    userTableBody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #999;">暂无用户数据</td></tr>';
                } else {
                    let html = '';
                    users.forEach(user => {
                        const roleText = user.role === 1 ? '管理员' : '普通用户';
                        const statusText = user.status === 0 ? '正常' : '禁言';
                        const statusClass = user.status === 0 ? 'status-normal' : 'status-banned';
                        const actionButton = user.role === 1 && user.username !== localStorage.getItem('adminUsername') ? 
                            '<button class="btn btn-warning btn-sm" disabled>无法操作</button>' : 
                            (user.status === 0 ? 
                                `<button class="btn btn-danger btn-sm" onclick="banUser(${user.id})">禁言</button>` : 
                                `<button class="btn btn-success btn-sm" onclick="unbanUser(${user.id})">解禁</button>`);
                        
                        html += `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.nickname || '-'}</td>
                                <td>${user.email || '-'}</td>
                                <td>${user.phone || '-'}</td>
                                <td>${user.coinBalance || 0}</td>
                                <td>${roleText}</td>
                                <td class="${statusClass}">${statusText}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" onclick="editUser(${user.id})">编辑</button>
                                    ${actionButton}
                                    ${user.role === 1 ? '' : `<button class="btn btn-danger btn-sm" onclick="deleteUser(${user.id})">删除</button>`}
                                </td>
                            </tr>
                        `;
                    });
                    
                    userTableBody.innerHTML = html;
                }
                
                // 更新分页
                if (pagination) {
                    updatePagination(pagination, page, totalPages, 'loadUserList');
                }
            }
        })
        .catch(error => {
            console.error('加载用户列表失败:', error);
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            if (userTableBody) {
                userTableBody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #ff4d4f;">加载失败，请稍后重试</td></tr>';
            }
        });
}

// 添加用户
function addUser() {
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    
    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.innerHTML = `
        <div class="modal-header">
            <h2>添加用户</h2>
            <span class="close" onclick="closeModal('addUserModal')">&times;</span>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label>用户名:</label>
                <input type="text" id="newUsername" class="form-input" placeholder="请输入用户名" />
            </div>
            <div class="form-group">
                <label>密码:</label>
                <input type="password" id="newPassword" class="form-input" placeholder="请输入密码" />
            </div>
            <div class="form-group">
                <label>昵称:</label>
                <input type="text" id="newNickname" class="form-input" placeholder="请输入昵称（可选）" />
            </div>
            <div class="form-group">
                <label>邮箱:</label>
                <input type="email" id="newEmail" class="form-input" placeholder="请输入邮箱（可选）" />
            </div>
            <div class="form-group">
                <label>电话:</label>
                <input type="tel" id="newPhone" class="form-input" placeholder="请输入电话（可选）" />
            </div>
            <div class="form-group">
                <label>初始金币:</label>
                <input type="number" id="newCoins" class="form-input" placeholder="请输入初始金币数量" value="0" min="0" />
            </div>
            <div class="form-group">
                <label>角色:</label>
                <select id="newRole" class="form-select">
                    <option value="0">普通用户</option>
                    <option value="1">管理员</option>
                </select>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-default" onclick="closeModal('addUserModal')">取消</button>
            <button class="btn btn-primary" onclick="submitAddUser()">确定</button>
        </div>
    `;
    
    modal.appendChild(modalContent);
    modal.id = 'addUserModal';
    document.body.appendChild(modal);
}

// 提交添加用户
function submitAddUser() {
    const username = document.getElementById('newUsername').value;
    const password = document.getElementById('newPassword').value;
    const nickname = document.getElementById('newNickname').value;
    const email = document.getElementById('newEmail').value;
    const phone = document.getElementById('newPhone').value;
    const coins = document.getElementById('newCoins').value;
    const role = document.getElementById('newRole').value;
    
    if (!username || !password) {
        alert('用户名和密码不能为空');
        return;
    }
    
    fetch('/knowledge-qa/api/admin/users', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username,
            password,
            nickname,
            email,
            phone,
            coinBalance: parseInt(coins) || 0,
            role: parseInt(role) || 0,
            status: 0
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('用户添加成功');
            closeModal('addUserModal');
            loadUserList(); // 重新加载用户列表
        } else {
            alert(data.message || '用户添加失败');
        }
    })
    .catch(error => {
        console.error('添加用户失败:', error);
        alert('添加用户失败，请稍后重试');
    });
}

// 编辑用户
function editUser(userId) {
    // 先获取用户信息
    fetch(`/knowledge-qa/api/admin/users/${userId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data) {
                const user = data.data;
                
                // 创建编辑用户模态框
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';
                
                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <div class="modal-header">
                        <h2>编辑用户</h2>
                        <span class="close" onclick="closeModal('editUserModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>用户名:</label>
                            <input type="text" id="editUsername" class="form-input" value="${user.username}" disabled />
                        </div>
                        <div class="form-group">
                            <label>密码:</label>
                            <input type="password" id="editPassword" class="form-input" placeholder="不修改请留空" />
                        </div>
                        <div class="form-group">
                            <label>昵称:</label>
                            <input type="text" id="editNickname" class="form-input" value="${user.nickname || ''}" />
                        </div>
                        <div class="form-group">
                            <label>邮箱:</label>
                            <input type="email" id="editEmail" class="form-input" value="${user.email || ''}" />
                        </div>
                        <div class="form-group">
                            <label>电话:</label>
                            <input type="tel" id="editPhone" class="form-input" value="${user.phone || ''}" />
                        </div>
                        <div class="form-group">
                            <label>金币余额:</label>
                            <input type="number" id="editCoins" class="form-input" value="${user.coinBalance || 0}" min="0" />
                        </div>
                        <div class="form-group">
                            <label>角色:</label>
                            <select id="editRole" class="form-select">
                                <option value="0" ${user.role === 0 ? 'selected' : ''}>普通用户</option>
                                <option value="1" ${user.role === 1 ? 'selected' : ''}>管理员</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>状态:</label>
                            <select id="editStatus" class="form-select">
                                <option value="0" ${user.status === 0 ? 'selected' : ''}>正常</option>
                                <option value="1" ${user.status === 1 ? 'selected' : ''}>禁言</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" onclick="closeModal('editUserModal')">取消</button>
                        <button class="btn btn-primary" onclick="submitEditUser(${userId})">确定</button>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                modal.id = 'editUserModal';
                document.body.appendChild(modal);
            } else {
                alert('获取用户信息失败');
            }
        })
        .catch(error => {
            console.error('获取用户信息失败:', error);
            alert('获取用户信息失败，请稍后重试');
        });
}

// 提交编辑用户
function submitEditUser(userId) {
    const password = document.getElementById('editPassword').value;
    const nickname = document.getElementById('editNickname').value;
    const email = document.getElementById('editEmail').value;
    const phone = document.getElementById('editPhone').value;
    const coins = document.getElementById('editCoins').value;
    const role = document.getElementById('editRole').value;
    const status = document.getElementById('editStatus').value;
    
    // 构建请求数据，不包含空密码
    const requestData = {
        nickname,
        email,
        phone,
        coinBalance: parseInt(coins) || 0,
        role: parseInt(role) || 0,
        status: parseInt(status) || 0
    };
    
    // 如果填写了密码，则包含密码
    if (password) {
        requestData.password = password;
    }
    
    fetch(`/knowledge-qa/api/admin/users/${userId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('用户编辑成功');
            closeModal('editUserModal');
            loadUserList(); // 重新加载用户列表
        } else {
            alert(data.message || '用户编辑失败');
        }
    })
    .catch(error => {
        console.error('编辑用户失败:', error);
        alert('编辑用户失败，请稍后重试');
    });
}

// 禁言用户
function banUser(userId) {
    if (confirm('确定要禁言该用户吗？')) {
        fetch(`/knowledge-qa/api/admin/users/${userId}/ban`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('用户禁言成功');
                loadUserList(); // 重新加载用户列表
            } else {
                alert(data.message || '用户禁言失败');
            }
        })
        .catch(error => {
            console.error('禁言用户失败:', error);
            alert('禁言用户失败，请稍后重试');
        });
    }
}

// 解禁用户
function unbanUser(userId) {
    if (confirm('确定要解禁该用户吗？')) {
        fetch(`/knowledge-qa/api/admin/users/${userId}/unban`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('用户解禁成功');
                loadUserList(); // 重新加载用户列表
            } else {
                alert(data.message || '用户解禁失败');
            }
        })
        .catch(error => {
            console.error('解禁用户失败:', error);
            alert('解禁用户失败，请稍后重试');
        });
    }
}

// 删除用户
function deleteUser(userId) {
    if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
        fetch(`/knowledge-qa/api/admin/users/${userId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('用户删除成功');
                loadUserList(); // 重新加载用户列表
            } else {
                alert(data.message || '用户删除失败');
            }
        })
        .catch(error => {
            console.error('删除用户失败:', error);
            alert('删除用户失败，请稍后重试');
        });
    }
}

// 加载问题列表
function loadQuestionList(page = 1) {
    const questionTableBody = document.getElementById('questionTableBody');
    const pagination = document.getElementById('questionPagination');
    const loadingIndicator = document.getElementById('loadingIndicator');
    
    // 获取搜索关键词和状态筛选
    let keyword = '';
    let status = 'all';
    if (document.getElementById('questionSearchInput')) {
        keyword = document.getElementById('questionSearchInput').value;
    }
    if (document.getElementById('questionStatusFilter')) {
        status = document.getElementById('questionStatusFilter').value;
    }
    
    if (loadingIndicator) {
        loadingIndicator.style.display = 'block';
    }
    
    fetch(`/knowledge-qa/api/admin/questions?page=${page}&pageSize=10&keyword=${encodeURIComponent(keyword)}&status=${status}`)
        .then(response => response.json())
        .then(data => {
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            
            if (data.code === 200 && questionTableBody) {
                const questions = data.data.questions || [];
                const total = data.data.total || 0;
                const pageSize = data.data.pageSize || 10;
                const totalPages = Math.ceil(total / pageSize);
                
                if (questions.length === 0) {
                    questionTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #999;">暂无问题数据</td></tr>';
                } else {
                    let html = '';
                    questions.forEach(question => {
                        const statusText = question.status === 0 ? '正常' : '已关闭';
                        const statusClass = question.status === 0 ? 'status-normal' : 'status-closed';
                        
                        html += `
                            <tr>
                                <td>${question.id}</td>
                                <td><a href="#" onclick="viewQuestionDetails(${question.id}); return false;">${question.title}</a></td>
                                <td>${question.username || '未知用户'}</td>
                                <td>${question.coinReward || 0}</td>
                                <td>${question.answerCount || 0}</td>
                                <td class="${statusClass}">${statusText}</td>
                                <td>${formatDate(question.createTime)}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" onclick="editQuestion(${question.id})">编辑</button>
                                    ${question.status === 0 ? 
                                        `<button class="btn btn-danger btn-sm" onclick="closeQuestion(${question.id})">关闭</button>` : 
                                        `<button class="btn btn-success btn-sm" onclick="openQuestion(${question.id})">开启</button>`}
                                    <button class="btn btn-danger btn-sm" onclick="deleteQuestion(${question.id})">删除</button>
                                </td>
                            </tr>
                        `;
                    });
                    
                    questionTableBody.innerHTML = html;
                }
                
                // 更新分页
                if (pagination) {
                    updatePagination(pagination, page, totalPages, 'loadQuestionList');
                }
            }
        })
        .catch(error => {
            console.error('加载问题列表失败:', error);
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            if (questionTableBody) {
                questionTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #ff4d4f;">加载失败，请稍后重试</td></tr>';
            }
        });
}

// 查看问题详情
function viewQuestionDetails(questionId) {
    // 获取问题详情
    fetch(`/knowledge-qa/api/admin/questions/${questionId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data) {
                const question = data.data;
                
                // 创建查看问题详情模态框
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';
                
                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <div class="modal-header">
                        <h2>问题详情</h2>
                        <span class="close" onclick="closeModal('questionDetailModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="detail-section">
                            <h3>${question.title}</h3>
                            <div class="question-meta">
                                <span class="question-author">提问者：${question.username || '未知用户'}</span>
                                <span class="question-time">发布时间：${formatDate(question.createTime)}</span>
                                <span class="question-reward">悬赏：${question.coinReward || 0} 金币</span>
                                <span class="question-status">状态：${question.status === 0 ? '正常' : '已关闭'}</span>
                            </div>
                            <div class="question-content">
                                ${question.content}
                            </div>
                        </div>
                        
                        <div class="detail-section">
                            <h4>回答列表 (${question.answerCount || 0} 个回答)</h4>
                            <div id="questionAnswersList">
                                <p>加载回答中...</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" onclick="closeModal('questionDetailModal')">关闭</button>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                modal.id = 'questionDetailModal';
                document.body.appendChild(modal);
                
                // 加载问题的回答列表
                loadQuestionAnswers(questionId);
            } else {
                alert('获取问题详情失败');
            }
        })
        .catch(error => {
            console.error('获取问题详情失败:', error);
            alert('获取问题详情失败，请稍后重试');
        });
}

// 加载问题的回答列表
function loadQuestionAnswers(questionId) {
    fetch(`/knowledge-qa/api/admin/questions/${questionId}/answers`)
        .then(response => response.json())
        .then(data => {
            const answersList = document.getElementById('questionAnswersList');
            if (data.code === 200 && answersList) {
                const answers = data.data || [];
                
                if (answers.length === 0) {
                    answersList.innerHTML = '<p class="no-data">暂无回答</p>';
                    return;
                }
                
                let html = '<div class="answers-container">';
                answers.forEach(answer => {
                    const isAccepted = answer.accepted ? '<span class="accepted-tag">已采纳</span>' : '';
                    
                    html += `
                        <div class="answer-item">
                            <div class="answer-header">
                                <span class="answer-author">回答者：${answer.username || '未知用户'}</span>
                                <span class="answer-time">回答时间：${formatDate(answer.createTime)}</span>
                                ${isAccepted}
                            </div>
                            <div class="answer-content">
                                ${answer.content}
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                
                answersList.innerHTML = html;
            }
        })
        .catch(error => {
            console.error('加载回答列表失败:', error);
            const answersList = document.getElementById('questionAnswersList');
            if (answersList) {
                answersList.innerHTML = '<p class="error-message">加载回答失败</p>';
            }
        });
}

// 编辑问题
function editQuestion(questionId) {
    // 先获取问题信息
    fetch(`/knowledge-qa/api/admin/questions/${questionId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data) {
                const question = data.data;
                
                // 创建编辑问题模态框
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';
                
                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <div class="modal-header">
                        <h2>编辑问题</h2>
                        <span class="close" onclick="closeModal('editQuestionModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>问题标题:</label>
                            <input type="text" id="editQuestionTitle" class="form-input" value="${question.title}" placeholder="请输入问题标题" />
                        </div>
                        <div class="form-group">
                            <label>悬赏金币:</label>
                            <input type="number" id="editQuestionReward" class="form-input" value="${question.coinReward || 0}" min="0" placeholder="请输入悬赏金币数量" />
                        </div>
                        <div class="form-group">
                            <label>问题内容:</label>
                            <textarea id="editQuestionContent" class="form-textarea" rows="8" placeholder="请输入问题详细描述">${question.content}</textarea>
                        </div>
                        <div class="form-group">
                            <label>问题状态:</label>
                            <select id="editQuestionStatus" class="form-select">
                                <option value="0" ${question.status === 0 ? 'selected' : ''}>正常</option>
                                <option value="1" ${question.status === 1 ? 'selected' : ''}>已关闭</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" onclick="closeModal('editQuestionModal')">取消</button>
                        <button class="btn btn-primary" onclick="submitEditQuestion(${questionId})">确定</button>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                modal.id = 'editQuestionModal';
                document.body.appendChild(modal);
            } else {
                alert('获取问题信息失败');
            }
        })
        .catch(error => {
            console.error('获取问题信息失败:', error);
            alert('获取问题信息失败，请稍后重试');
        });
}

// 提交编辑问题
function submitEditQuestion(questionId) {
    const title = document.getElementById('editQuestionTitle').value;
    const reward = document.getElementById('editQuestionReward').value;
    const content = document.getElementById('editQuestionContent').value;
    const status = document.getElementById('editQuestionStatus').value;
    
    if (!title || !content) {
        alert('问题标题和内容不能为空');
        return;
    }
    
    fetch(`/knowledge-qa/api/admin/questions/${questionId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title,
            content,
            coinReward: parseInt(reward) || 0,
            status: parseInt(status) || 0
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('问题编辑成功');
            closeModal('editQuestionModal');
            loadQuestionList(); // 重新加载问题列表
        } else {
            alert(data.message || '问题编辑失败');
        }
    })
    .catch(error => {
        console.error('编辑问题失败:', error);
        alert('编辑问题失败，请稍后重试');
    });
}

// 关闭问题
function closeQuestion(questionId) {
    if (confirm('确定要关闭该问题吗？')) {
        fetch(`/knowledge-qa/api/admin/questions/${questionId}/close`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('问题关闭成功');
                loadQuestionList(); // 重新加载问题列表
            } else {
                alert(data.message || '问题关闭失败');
            }
        })
        .catch(error => {
            console.error('关闭问题失败:', error);
            alert('关闭问题失败，请稍后重试');
        });
    }
}

// 开启问题
function openQuestion(questionId) {
    if (confirm('确定要开启该问题吗？')) {
        fetch(`/knowledge-qa/api/admin/questions/${questionId}/open`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('问题开启成功');
                loadQuestionList(); // 重新加载问题列表
            } else {
                alert(data.message || '问题开启失败');
            }
        })
        .catch(error => {
            console.error('开启问题失败:', error);
            alert('开启问题失败，请稍后重试');
        });
    }
}

// 删除问题
function deleteQuestion(questionId) {
    if (confirm('确定要删除该问题吗？此操作不可恢复，同时会删除相关的回答！')) {
        fetch(`/knowledge-qa/api/admin/questions/${questionId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('问题删除成功');
                loadQuestionList(); // 重新加载问题列表
            } else {
                alert(data.message || '问题删除失败');
            }
        })
        .catch(error => {
            console.error('删除问题失败:', error);
            alert('删除问题失败，请稍后重试');
        });
    }
}

// 加载回答列表
function loadAnswerList(page = 1) {
    const answerTableBody = document.getElementById('answerTableBody');
    const pagination = document.getElementById('answerPagination');
    const loadingIndicator = document.getElementById('loadingIndicator');
    
    // 获取搜索关键词和状态筛选
    let keyword = '';
    let status = 'all';
    if (document.getElementById('answerSearchInput')) {
        keyword = document.getElementById('answerSearchInput').value;
    }
    if (document.getElementById('answerStatusFilter')) {
        status = document.getElementById('answerStatusFilter').value;
    }
    
    if (loadingIndicator) {
        loadingIndicator.style.display = 'block';
    }
    
    fetch(`/knowledge-qa/api/admin/answers?page=${page}&pageSize=10&keyword=${encodeURIComponent(keyword)}&status=${status}`)
        .then(response => response.json())
        .then(data => {
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            
            if (data.code === 200 && answerTableBody) {
                const answers = data.data.answers || [];
                const total = data.data.total || 0;
                const pageSize = data.data.pageSize || 10;
                const totalPages = Math.ceil(total / pageSize);
                
                if (answers.length === 0) {
                    answerTableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">暂无回答数据</td></tr>';
                } else {
                    let html = '';
                    answers.forEach(answer => {
                        const statusText = answer.status === 0 ? '正常' : '已删除';
                        const statusClass = answer.status === 0 ? 'status-normal' : 'status-deleted';
                        
                        // 截取回答内容，过长的内容显示省略号
                        const contentPreview = answer.content.length > 100 ? answer.content.substring(0, 100) + '...' : answer.content;
                        
                        html += `
                            <tr>
                                <td>${answer.id}</td>
                                <td><a href="#" onclick="viewAnswerDetails(${answer.id}); return false;">${contentPreview}</a></td>
                                <td>${answer.questionTitle || '未知问题'}</td>
                                <td>${answer.username || '未知用户'}</td>
                                <td class="${statusClass}">${statusText}</td>
                                <td>${formatDate(answer.createTime)}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" onclick="editAnswer(${answer.id})">编辑</button>
                                    ${answer.status === 0 ? 
                                        `<button class="btn btn-danger btn-sm" onclick="deleteAnswer(${answer.id})">删除</button>` : 
                                        `<button class="btn btn-success btn-sm" onclick="restoreAnswer(${answer.id})">恢复</button>`}
                                </td>
                            </tr>
                        `;
                    });
                    
                    answerTableBody.innerHTML = html;
                }
                
                // 更新分页
                if (pagination) {
                    updatePagination(pagination, page, totalPages, 'loadAnswerList');
                }
            }
        })
        .catch(error => {
            console.error('加载回答列表失败:', error);
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            if (answerTableBody) {
                answerTableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #ff4d4f;">加载失败，请稍后重试</td></tr>';
            }
        });
}

// 查看回答详情
function viewAnswerDetails(answerId) {
    // 获取回答详情
    fetch(`/knowledge-qa/api/admin/answers/${answerId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data) {
                const answer = data.data;
                
                // 创建查看回答详情模态框
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';
                
                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <div class="modal-header">
                        <h2>回答详情</h2>
                        <span class="close" onclick="closeModal('answerDetailModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="detail-section">
                            <div class="answer-meta">
                                <span class="answer-author">回答者：${answer.username || '未知用户'}</span>
                                <span class="answer-time">回答时间：${formatDate(answer.createTime)}</span>
                                <span class="answer-status">状态：${answer.status === 0 ? '正常' : '已删除'}</span>
                                ${answer.accepted ? '<span class="accepted-tag">已采纳</span>' : ''}
                            </div>
                            <div class="answer-content">
                                ${answer.content}
                            </div>
                        </div>
                        
                        <div class="detail-section">
                            <h4>所属问题</h4>
                            <div class="question-reference">
                                <a href="#" onclick="viewQuestionDetails(${answer.questionId}); closeModal('answerDetailModal'); return false;">${answer.questionTitle || '未知问题'}</a>
                                <p>提问者：${answer.questionUsername || '未知用户'}</p>
                                <p>悬赏金币：${answer.questionReward || 0}</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" onclick="closeModal('answerDetailModal')">关闭</button>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                modal.id = 'answerDetailModal';
                document.body.appendChild(modal);
            } else {
                alert('获取回答详情失败');
            }
        })
        .catch(error => {
            console.error('获取回答详情失败:', error);
            alert('获取回答详情失败，请稍后重试');
        });
}

// 编辑回答
function editAnswer(answerId) {
    // 先获取回答信息
    fetch(`/knowledge-qa/api/admin/answers/${answerId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data) {
                const answer = data.data;
                
                // 创建编辑回答模态框
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';
                
                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <div class="modal-header">
                        <h2>编辑回答</h2>
                        <span class="close" onclick="closeModal('editAnswerModal')">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>所属问题:</label>
                            <div class="question-reference">
                                <a href="#" onclick="viewQuestionDetails(${answer.questionId}); return false;">${answer.questionTitle || '未知问题'}</a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>回答内容:</label>
                            <textarea id="editAnswerContent" class="form-textarea" rows="8" placeholder="请输入回答内容">${answer.content}</textarea>
                        </div>
                        <div class="form-group">
                            <label>回答状态:</label>
                            <select id="editAnswerStatus" class="form-select">
                                <option value="0" ${answer.status === 0 ? 'selected' : ''}>正常</option>
                                <option value="1" ${answer.status === 1 ? 'selected' : ''}>已删除</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" onclick="closeModal('editAnswerModal')">取消</button>
                        <button class="btn btn-primary" onclick="submitEditAnswer(${answerId})">确定</button>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                modal.id = 'editAnswerModal';
                document.body.appendChild(modal);
            } else {
                alert('获取回答信息失败');
            }
        })
        .catch(error => {
            console.error('获取回答信息失败:', error);
            alert('获取回答信息失败，请稍后重试');
        });
}

// 提交编辑回答
function submitEditAnswer(answerId) {
    const content = document.getElementById('editAnswerContent').value;
    const status = document.getElementById('editAnswerStatus').value;
    
    if (!content) {
        alert('回答内容不能为空');
        return;
    }
    
    fetch(`/knowledge-qa/api/admin/answers/${answerId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            content,
            status: parseInt(status) || 0
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('回答编辑成功');
            closeModal('editAnswerModal');
            loadAnswerList(); // 重新加载回答列表
        } else {
            alert(data.message || '回答编辑失败');
        }
    })
    .catch(error => {
        console.error('编辑回答失败:', error);
        alert('编辑回答失败，请稍后重试');
    });
}

// 删除回答
function deleteAnswer(answerId) {
    if (confirm('确定要删除该回答吗？')) {
        fetch(`/knowledge-qa/api/admin/answers/${answerId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('回答删除成功');
                loadAnswerList(); // 重新加载回答列表
            } else {
                alert(data.message || '回答删除失败');
            }
        })
        .catch(error => {
            console.error('删除回答失败:', error);
            alert('删除回答失败，请稍后重试');
        });
    }
}

// 恢复回答
function restoreAnswer(answerId) {
    if (confirm('确定要恢复该回答吗？')) {
        fetch(`/knowledge-qa/api/admin/answers/${answerId}/restore`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('回答恢复成功');
                loadAnswerList(); // 重新加载回答列表
            } else {
                alert(data.message || '回答恢复失败');
            }
        })
        .catch(error => {
            console.error('恢复回答失败:', error);
            alert('恢复回答失败，请稍后重试');
        });
    }
}

// 加载交易列表
function loadTransactionList(page = 1) {
    const transactionTableBody = document.getElementById('transactionTableBody');
    const pagination = document.getElementById('transactionPagination');
    const loadingIndicator = document.getElementById('loadingIndicator');
    
    // 获取搜索关键词和类型筛选
    let keyword = '';
    let type = 'all';
    if (document.getElementById('transactionSearchInput')) {
        keyword = document.getElementById('transactionSearchInput').value;
    }
    if (document.getElementById('transactionTypeFilter')) {
        type = document.getElementById('transactionTypeFilter').value;
    }
    
    if (loadingIndicator) {
        loadingIndicator.style.display = 'block';
    }
    
    fetch(`/knowledge-qa/api/admin/transactions?page=${page}&pageSize=10&username=${encodeURIComponent(keyword)}&type=${type}`)
        .then(response => response.json())
        .then(data => {
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            
            if (data.code === 200 && transactionTableBody) {
                const transactions = data.data.transactions || [];
                const total = data.data.total || 0;
                const pageSize = data.data.pageSize || 10;
                const totalPages = Math.ceil(total / pageSize);
                
                if (transactions.length === 0) {
                    transactionTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #999;">暂无交易记录</td></tr>';
                } else {
                    let html = '';
                    transactions.forEach(transaction => {
                        // 根据交易类型显示不同的文本和样式
                        let typeText = '';
                        let typeClass = '';
                        let amountDisplay = '';
                        
                        switch(transaction.type) {
                            case 0:
                                typeText = '充值';
                                typeClass = 'type-recharge';
                                amountDisplay = `+${transaction.amount}`;
                                break;
                            case 1:
                                typeText = '发布悬赏扣款';
                                typeClass = 'type-question';
                                amountDisplay = `-${transaction.amount}`;
                                break;
                            case 2:
                                typeText = '打赏';
                                typeClass = 'type-reward';
                                amountDisplay = `-${transaction.amount}`;
                                break;
                            case 3:
                                typeText = '其他';
                                typeClass = '';
                                amountDisplay = transaction.amount > 0 ? `+${transaction.amount}` : transaction.amount;
                                break;
                            default:
                                typeText = '未知类型';
                                typeClass = '';
                                amountDisplay = transaction.amount;
                        }
                        
                        html += `
                            <tr>
                                <td>${transaction.id}</td>
                                <td>${transaction.username || '未知用户'}</td>
                                <td class="${typeClass}">${typeText}</td>
                                <td class="amount">${amountDisplay}</td>
                                <td>${transaction.balanceAfter || 0}</td>
                                <td>${formatDate(transaction.createTime)}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" onclick="viewTransactionDetails(${transaction.id})">查看</button>
                                </td>
                            </tr>
                        `;
                    });
                    
                    transactionTableBody.innerHTML = html;
                }
                
                // 更新分页
                if (pagination) {
                    updatePagination(pagination, page, totalPages, 'loadTransactionList');
                }
            }
        })
        .catch(error => {
            console.error('加载交易列表失败:', error);
            if (loadingIndicator) {
                loadingIndicator.style.display = 'none';
            }
            if (transactionTableBody) {
                transactionTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #ff4d4f;">加载失败，请稍后重试</td></tr>';
            }
        });
}

// 查看交易详情
function viewTransactionDetails(transactionId) {
    // 由于后端没有提供获取单个交易详情的接口，我们使用现有的交易列表接口，并在前端过滤
    fetch(`/knowledge-qa/api/admin/transactions?page=1&pageSize=1000`) // 获取足够多的交易记录
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data && data.data.transactions) {
                const transaction = data.data.transactions.find(t => t.id === transactionId);
                
                if (transaction) {
                    // 根据交易类型显示不同的文本
                    let typeText = '';
                    let amountDisplay = transaction.amount > 0 ? `+${transaction.amount}` : transaction.amount;
                    
                    switch(transaction.type) {
                        case 0:
                            typeText = '充值';
                            break;
                        case 1:
                            typeText = '发布悬赏扣款';
                            break;
                        case 2:
                            typeText = '打赏';
                            break;
                        case 3:
                            typeText = '其他';
                            break;
                        default:
                            typeText = '未知类型';
                    }
                    
                    // 创建模态框
                    const modal = document.createElement('div');
                    modal.className = 'modal';
                    modal.style.display = 'block';
                    
                    const modalContent = document.createElement('div');
                    modalContent.className = 'modal-content';
                    modalContent.innerHTML = `
                        <div class="modal-header">
                            <h2>交易详情</h2>
                            <span class="close" onclick="closeModal('transactionDetailModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <div class="detail-item">
                                <span class="detail-label">交易ID:</span>
                                <span class="detail-value">${transaction.id}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">用户:</span>
                                <span class="detail-value">${transaction.username || '未知用户'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">交易类型:</span>
                                <span class="detail-value">${typeText}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">金币数量:</span>
                                <span class="detail-value">${amountDisplay}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">用户余额:</span>
                                <span class="detail-value">${transaction.balanceAfter || 0}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">交易时间:</span>
                                <span class="detail-value">${formatDate(transaction.createTime)}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">备注:</span>
                                <span class="detail-value">${transaction.remark || '无'}</span>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary" onclick="closeModal('transactionDetailModal')">关闭</button>
                        </div>
                    `;
                    
                    modal.appendChild(modalContent);
                    modal.id = 'transactionDetailModal';
                    document.body.appendChild(modal);
                } else {
                    alert('未找到该交易记录');
                }
            } else {
                alert('获取交易列表失败');
            }
        })
        .catch(error => {
            console.error('获取交易列表失败:', error);
            alert('获取交易列表失败，请稍后重试');
        });
}

// 关闭模态框的通用函数
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.remove();
    }
}

// 搜索用户
function searchUsers() {
    loadUserList(1); // 从第一页重新加载
}

// 搜索问题
function searchQuestions() {
    loadQuestionList(1); // 从第一页重新加载
}

// 搜索回答
function searchAnswers() {
    loadAnswerList(1); // 从第一页重新加载
}

// 搜索交易记录
function searchTransactions() {
    loadTransactionList(1); // 从第一页重新加载
}

// 更新分页
function updatePagination(paginationElement, currentPage, totalPages, callbackFunction) {
    if (totalPages <= 1) {
        paginationElement.innerHTML = '';
        return;
    }
    
    let html = '<div class="pagination">';
    
    // 上一页
    if (currentPage > 1) {
        html += `<button class="page-btn" onclick="${callbackFunction}(${currentPage - 1})">上一页</button>`;
    } else {
        html += '<button class="page-btn disabled">上一页</button>';
    }
    
    // 页码
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, startPage + 4);
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            html += `<button class="page-btn active" onclick="${callbackFunction}(${i})"><strong>${i}</strong></button>`;
        } else {
            html += `<button class="page-btn" onclick="${callbackFunction}(${i})">${i}</button>`;
        }
    }
    
    // 下一页
    if (currentPage < totalPages) {
        html += `<button class="page-btn" onclick="${callbackFunction}(${currentPage + 1})">下一页</button>`;
    } else {
        html += '<button class="page-btn disabled">下一页</button>';
    }
    
    html += '</div>';
    paginationElement.innerHTML = html;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}